import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const permissions = ref([])

  const isLoggedIn = computed(() => !!token.value)

  const initUser = async () => {
    if (token.value) {
      try {
        const info = await getUserInfo()
        userInfo.value = info.data
      } catch (error) {
        logout()
      }
    }
  }

  const loginAction = async (loginForm) => {
    try {
      const response = await login(loginForm)
      token.value = response.data.token
      userInfo.value = response.data.userInfo
      localStorage.setItem('token', token.value)
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    localStorage.removeItem('token')
  }

  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  return {
    token,
    userInfo,
    permissions,
    isLoggedIn,
    initUser,
    loginAction,
    logout,
    hasPermission
  }
})
